#-*- coding:utf-8 -*-
import numpy as np
import json,os
from vno_data import *
from vno import *
import pandas as pd
# 小数点个数
DOUBLE_PRECISION = 6

def creat_dir(dirs):
    if not os.path.exists(dirs):
        os.makedirs(dirs)

# 处理Dataframe格式中ID对应的值
def processing_ids(df_datas):
    id_labels = []
    tmp_dict = {}
    # 只要包含'id'的字符串都处理
    # 列名包含's'和't'也处理
    for col in df_datas.columns:
        if 'id' in col:
            id_labels.append(col)
            tmp_dict[col] = np.str
    if 's' in df_datas.columns:
        id_labels.append('s')
        tmp_dict['s'] = np.str
    if 't' in df_datas.columns:
        id_labels.append('t')
        tmp_dict['t'] = np.str
    # 将id转为字符串
    df_datas = df_datas.astype(tmp_dict)
    # 复制一组数据
    df = df_datas[id_labels]
    df_datas.drop(labels=id_labels,axis=1,inplace = True)
    # 遍历所有行
    for index in df.index:
        # 遍历所有行对应的ID列
        for id_label in id_labels:
            # print(df.loc[index][id_label])
            # 如果为空，则指定为None
            if df.loc[index][id_label] == 'nan':
                df.loc[index][id_label] = None
                continue
            # 因为id要么就是整数，要么就是字符串，不应该出现.0这样的现象
            # 所有将'.0'替换
            s = df.loc[index][id_label]
            df.loc[index][id_label] = s.replace('.0','')
    return pd.concat([df,df_datas],axis=1)

def read_csv_file(file_name,coding = 'utf-8'):
    if not os.path.exists(file_name):
        return []
    data = open(file_name).read()
    ret = []
    if len(data) > 1:
        df = pd.read_csv(file_name,engine='python',encoding=coding)
        # 将id转为字符串
        df = processing_ids(df)
        json_str = df.to_json(orient='records')
        ret = json.loads(json_str.replace("\'","\""))
    return ret

def creat_json_by_csv(csv_dir,save_json_file=None,coding='utf-8'):
    # 读取分支数据
    edge_json = read_csv_file(csv_dir+'edges.csv',coding=coding)
    # 读取节点数据
    node_json = read_csv_file(csv_dir+'nodes.csv',coding=coding)
    # 读取风机数据
    tmp_fans = read_csv_file(csv_dir+'fans.csv',coding=coding)
    # fan_json = []
    fan_json = tmp_fans
    # for fan in tmp_fans:
    #     if fan['fan_used']:
    #         fan_json.append(fan)
    # 读取构筑物数据
    struct_json = read_csv_file(csv_dir+'structs.csv',coding=coding)
    # 读取节点压差传感器数据
    sensor_hs_json = read_csv_file(csv_dir+'sensor_h.csv',coding=coding)
    # 读取风量传感器数据
    sensor_qs_json = read_csv_file(csv_dir+'sensor_q.csv',coding=coding)
    json_datas = {
        'edge_set':edge_json,
        'node_set':node_json,
        'fan_set':fan_json,
        'struct_set':struct_json,
        'sensor_hs_set':sensor_hs_json,
        'sensor_qs_set':sensor_qs_json
    }
    if save_json_file is not None:
        f = open(save_json_file, 'w')
        json.dump(json_datas, f, indent=4)
        f.close()
    return json_datas

def creat_graph_json_datas(pro_datas, graph_file):
    # pro_datas = read_json_file(pro_file)
    edge_set = pro_datas['edge_set']
    fan_set = pro_datas['fan_set']
    struct_set = pro_datas['struct_set']
    node_set = pro_datas['node_set']
    # edges = []
    fans = []
    # nodes = []
    # structs = []
    qFixs = []
    config = read_json_file('./datas/config.json')['vno_config']

    # for st in struct_set:
    #     tmp_dic = {}
    #     for k in st.keys():
    #         tmp_dic[k] = st[k]
    #     structs.append(tmp_dic)
    for ed in edge_set:
        # tmp_dic = {}
        st_r = 0
        for st in struct_set:
            if st['e_id'] == ed['id'] and st['r0'] is not None and st['delta_r'] is not None:
                st_r = st['r0']
                break
        # 巷道的风阻=初始风阻+构筑物初始风阻
        ed['r'] = ed['r0']+st_r
        ed['r0'] = ed['r0']
        # for 
        # edges.append(tmp_dic)
    init_flag = 1
    for fd in fan_set:
        if fd['fan_flag'] < 0:
            init_flag = -1
        fans.append({'a0':fd['a0'],'a1':fd['a1'],'a2':fd['a2'],'e_id':fd['e_id'],'fan_flag':fd['fan_flag']})

    # for nd in node_set:
    #     tmp_dic = {}
    #     for k in nd.keys():
    #         tmp_dic[k] = nd[k]
    #     nodes.append(tmp_dic)

    graph_datas = {
        "edges":edge_set,
        "fans": fans,
        "nodes":node_set,
        "structs":struct_set,
        "maxCount": config['maxCount'],
        "q_precise": config['q_precise'],
        "h_precise": config['h_precise'],
        "Q": init_flag*config['Q'],
        "qFixs": qFixs,
        'p_used_fans': config['p_used_fans']
    }
    f = open(graph_file, 'w')
    json.dump(graph_datas, f, indent=4)
    f.close()


if __name__ == '__main__':
    pro_datas = creat_json_by_csv('./datas/jc/')
    creat_graph_json_datas(pro_datas,'./datas/jc/graph_jc.json')
